package com.deyang.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.Transformation;
import com.deyang.config.ConfigRes;
import com.deyang.config.GlideApp;
import com.deyang.config.IntentConfig;
import com.deyang.maillist.R;
import com.deyang.ui.activity.ShowImagesActivity;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


/**
 * 图像工具
 * Created by Administrator on 2017/3/7 0007.
 */

public class ImageUtil {

    private static final String TAG = "ImageUtil";


    /**
     * 是否显示圆角，第三个参数为true
     *
     * @param imageView 图像控件
     * @param resUrl    图片地址
     */
    public static void loadImage(Context context, ImageView imageView, Object resUrl, Integer failRes) {
//        DrawableTransitionOptions drawableTransitionOptions = new DrawableTransitionOptions();
//        drawableTransitionOptions.crossFade(500);

//        RequestOptions requestOptions = new RequestOptions();
//        requestOptions.placeholder(R.drawable.loading);

        GlideApp.with(context)
                .load(resUrl)
                .placeholder(R.drawable.loading)
                .error(failRes)
                .into(imageView);
    }

    /**
     * 是否显示圆型，第三个参数为true
     *
     * @param context
     * @param imageView
     * @param resUrl         图片地址
     * @param failRes        加载失败图片
     * @param transformation 样式 参考↓
     *                       CropTransformation              图片进行裁剪 然后根据裁剪大小进行铺满
     *                       CropCircleTransformation        圆形
     *                       CropSquareTransformation        横向铺满  造成高度截取
     *                       RoundedCornersTransformation    圆角  参数：弧度，  内边距
     *                       ColorFilterTransformation       不晓得  颜色过滤？ 闪退
     *                       GrayscaleTransformation         黑白色
     *                       BlurTransformation              高斯模糊
     *                       MaskTransformation              不晓得
     */
    public static void loadImage(Context context, ImageView imageView, Object resUrl, Integer failRes, Transformation transformation) {
        GlideApp.with(context).load(resUrl)
                .transform(transformation)
                .placeholder(R.drawable.loading)
                .error(failRes)
                .into(imageView);
    }


    /**
     * 展示图片
     *
     * @param activity
     * @param images
     * @param imagePosition
     */
    public static void showImages(Activity activity, String images, int imagePosition) {
        Intent intent = new Intent(activity, ShowImagesActivity.class);
        intent.putExtra(IntentConfig.SHOW_IMAGES, images);
        intent.putExtra(IntentConfig.SHOW_IMAGES_position, imagePosition);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.scale_translate, R.anim.alpha_action);
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 质量压缩图片，图片占用内存减小，像素数不变，常用于上传
     *
     * @param image
     * @param size    期望图片的大小，单位为kb
     * @param options 图片压缩的质量，取值1-100，越小表示压缩的越厉害,如输入30，表示压缩70%
     * @return
     */
    public static Bitmap compressImage(Bitmap image, int size, int options) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > size) {
            options -= 20;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            // 这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    public static Bitmap revitionImageSize(String path) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                new File(path)));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            if ((options.outWidth >> i <= 1000)
                    && (options.outHeight >> i <= 1000)) {
                in = new BufferedInputStream(
                        new FileInputStream(new File(path)));
                options.inSampleSize = (int) Math.pow(2.0D, i);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeStream(in, null, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }

    /**
     * 根据 imageview 保存 图片   到本地
     *
     * @param typePath
     * @param imageView
     */
    public static void saveImage(String typePath, ImageView imageView) {
        if (imageView.getDrawable() != null) {
            imageView.buildDrawingCache();
            Bitmap bitmap = imageView.getDrawingCache();
            ImageUtil.saveBitmap(typePath, bitmap);
        }
    }

    /**
     * 保存bitmap到本地
     *
     * @param typePath
     * @param mBitmap
     * @return
     */
    public static String saveBitmap(String typePath, Bitmap mBitmap) {
        String savePath = ConfigRes.Image + "/";

        try {
            File file = new File(savePath + typePath);
            if (!file.exists() || !file.isDirectory()) {
                file.mkdirs();
            }
            File imagefile = new File(file, UUID.randomUUID().toString() + ".jpeg");
            imagefile.createNewFile();
            FileOutputStream fos = new FileOutputStream(imagefile);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
            return imagefile.getAbsolutePath();
        } catch (IOException e) {
            ToastUtil.showError("上传文件失败");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64 转 图片
     *
     * @param string
     * @return
     */
    public static Bitmap base64ToBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    /**
     * 获取 view 对应的bitmap
     *
     * @param v
     * @return
     */
    public static Bitmap getBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
//        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }


}
